package com.cskaoyan.service;

import com.cskaoyan.bean.PO.MarketStorage;
import com.cskaoyan.mapper.MarketStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName WxStorageServiceImpl
 * @Description TODO
 * @Author ke
 * @Date 2022/8/18 11:47
 * @Version 1.0
 */
@Service
public class WxStorageServiceImpl implements WxStorageService {

    @Autowired
    MarketStorageMapper marketStorageMapper;

    @Override
    public MarketStorage upload(MultipartFile file) throws IOException {
        if (file==null){
            return null;
        }
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取随机前缀,因为如果上传文件名字一样的话会被覆盖,所以要使用UUID
        String random = UUID.randomUUID().toString().replaceAll("-", "");
        // 说的是获取请求参数名字,一会debug试试
        String name = file.getName();
        // 获取正文类型 image/jpeg 文件的类型
        String contentType = file.getContentType();
        // 获取文件的大小
        long size = file.getSize();
        // 例如把xxx.jpg 变成 ["xxx","jpg"],这里的.还用到了转义字符
        String[] split = originalFilename.split("\\.");
        // 生成最终保存下来的文件名
        String fileName=random+"."+split[split.length-1];

        // 最后还有保存文件
        File file1 = new File("c://spring/",fileName);
        file.transferTo(file1);

        MarketStorage storage = new MarketStorage();

        storage.setKey(fileName);
        storage.setName(originalFilename);
        storage.setType(contentType);
        storage.setSize(size);
        storage.setUrl("http://localhost:8083/pic/"+fileName);
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());

        marketStorageMapper.insertSelective(storage);

        return storage;
    }
}
